import Taro from "@tarojs/taro";
import { View, ScrollView } from "@tarojs/components";
import { Cell, InfiniteLoading } from "@nutui/nutui-react-taro";
import { useState, useEffect } from "react";
import AuthUtil from "../../utils/api/auth"; // 引入你的 API 工具
import "./index.less";
import { log } from "console";

const sleep = (time: number): Promise<unknown> =>
  new Promise((resolve) => {
    setTimeout(resolve, time);
  });

function Agreement() {
  const [orders, setOrders] = useState([]); // 初始化订单列表
  const [hasMore, setHasMore] = useState(true); // 是否有更多数据
  const [page, setPage] = useState(1); // 当前页码

  // 获取订单列表的函数
  const getOrderList = async (page) => {
    try {
      Taro.showLoading({ title: "加载中..." }); // 显示加载中的Toast
      // 人为添加一个延时，例如500毫秒
      await new Promise((resolve) => setTimeout(resolve, 500));
      const response = await AuthUtil.getOrder(page); // 调用你的 API 方法
      if (response && response.data) {
        const formattedOrders = response.data.map((order) => {
          const approve =
            order.orderStatus?.id === 4
              ? "审批通过"
              : order.orderStatus?.id === 3
              ? "审批不通过"
              : order.orderStatus?.id === 2
              ? "审核中"
              : order.orderStatus?.id === 1
              ? "未提交"
              : ""; // const orderStatus =order.orderStatus ==='label'?
          const status = order.orderStatus.label; // 根据状态字典映射状态
          const publishedDate = formatDateTime(order.publishedAt); // 格式化日期为更易读的格式
          return {
            ...order,
            status,
            publishedDate,
            approve,
          };
        });
        Taro.hideLoading(); // 获取数据成功后隐藏Toast
        if (formattedOrders.length === 0) {
          setHasMore(false); // 如果没有更多数据，更新状态
        } else {
          if (page === 1) {
            setOrders(formattedOrders);
          } else {
            Taro.hideLoading(); // 获取数据成功后隐藏Toast
            setOrders((prevOrders) => [...prevOrders, ...formattedOrders]); // 更新订单状态
          }
        }
      }
      Taro.hideLoading();
    } catch (error) {
      Taro.hideLoading(); // 获取数据成功后隐藏Toast
      console.error("获取订单列表失败:", error);
    }
  };

  // 组件加载时获取订单列表
  useEffect(() => {
    getOrderList(page);
  }, [page]); // 依赖于页码

  // 格式化日期时间
  const formatDateTime = (dateTimeStr) => {
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };

  const goPage = (value) => {
    const url =
      value?.payStatus && value?.orderStatus?.id !== 4
        ? "/pages/editContent/index"
        : "/pages/detail/index";
    if (value.orderStatus)
      return Taro.navigateTo({ url: `${url}?value=${JSON.stringify(value)}` });
  };

  const loadMore = async () => {
    console.log("尝试加载更多数据，当前页码:", page); // 调试输出
    if (hasMore) {
      console.log("开始加载更多数据");
      await sleep(2000); // 模拟加载延迟
      setPage((prevPage) => prevPage + 1); // 增加页码以加载更多数据
    } else {
      console.log("没有更多数据可加载");
    }
  };

  const content =
    orders.length > 0 ? (
      orders.map((order, index) => (
        <View key={index} className="order-item" onClick={() => goPage(order)}>
          <View className="order">
            订单类型：{order?.sellerType === "company" ? "公司" : "个人"}
          </View>
          <View className="order">申请时间：{order?.publishedDate}</View>
          <View className="order">车主姓名：{order?.realName}</View>
          <View className="order">订单状态：{order?.status}</View>
        </View>
      ))
    ) : (
      <View className="no-data">暂无数据</View>
    );

  return (
    <ScrollView
      className="agreement"
      style={{ height: "100vh", overflowY: "auto" }}
      scrollY
      onScrollToLower={loadMore} // 使用 onScrollToLower 事件
    >
      <Cell>
        <InfiniteLoading
          pullRefresh={true}
          hasMore={hasMore}
          loadingText="加载中..."
          loadMoreText="没有更多了"
        >
          {content}
        </InfiniteLoading>
      </Cell>
    </ScrollView>
  );
}

export default Agreement;
